<?php

// +----------------------------------------------------------------------

namespace app\user\home;

use app\common\controller\BaseController;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use app\user\model\Level as LevelModel;
use app\user\model\Message as MessageModel;
use util\Wxsdk;
use think\facade\Db;

/**
 * 前端用户控制器
 * @package app\user\home
 */
class Member extends BaseController
{
	public function wxlogin()
	{
		// 获取传参
		$param = request()->param();
		
		// 判断登录
		$uid = is_login();
		
		// 回调路径
		if (!cookie('__backurl__')) cookie('__backurl__', url('user/member/index'));
		
		if (!$uid){
			// 是否微信回调
			if(!isset($param['code']) || !isset($param['state']) ){
				// 是否借用登录
				$out = urlencode(config('wechat.out'));
				if ($out){
					$url = $out;
					$re_url = real_url('user/member/wxlogin');
					$re_url = urlencode($re_url);
					$api = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat.appid').'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state='.$re_url.'#wechat_redirect';
				}else{
					$url = real_url('user/member/wxlogin');
					$url = urlencode($url);
					$api = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat.appid').'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=ok#wechat_redirect';
				}
				return redirect($api);
			} else {
				
				//微信回调后，换取TOKEN
				$api = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wechat.appid').'&secret='.config('wechat.appsecret').'&code='.$param['code'].'&grant_type=authorization_code';
				$get_token = json_decode(post_curls($api, []), true);
				
				if(isset($get_token['access_token'])){
					
					// 获取用户基本资料
					$userinfo = [];
					$api = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$get_token['access_token'].'&openid='.$get_token['openid'].'&lang=zh_CN';
					
					$userinfo = json_decode(post_curls($api, []), true);

					if(isset($userinfo['errcode']) || !$userinfo) $this->error('登录失败');

					// 截取openid字段7-16位
					$username = 'wx_'.mb_substr($get_token['openid'], 6, 10);
					if ($this->emoji($userinfo['nickname'])) $userinfo['nickname'] = $username;
					$userfile['nickname'] = $userinfo['nickname'];
					
					$userfile['openid'] = $get_token['openid'];
					$userfile['key']	= $get_token['openid'];
					$userfile['role']	= 'wechat';
					if (isset($userinfo['unionid']) && $userinfo['unionid'] != '') $userfile['unionid'] = $userinfo['unionid'];
					if (isset($userinfo['headimgurl'])) $userfile['avatar_img'] = $userinfo['headimgurl'];
					
					$userfile['sex'] = $userinfo['sex'];
					$MemberModel = new MemberModel;
					$result = $MemberModel->saveData($userfile);
					if($result === false){
						$this->error($MemberModel->getError());
					}
					return redirect(cookie('__backurl__'));
				}else{
					$this->error('登录失败('.$get_token['errcode'].')');
				}
			}
		}else{
			return redirect(cookie('__backurl__'));
		}
	}
	/**
	 * 用户首页
	 * @author paulxun
	 * @return fetch|view
	 */
	public function index()
	{
		// 获取浏览器类型
		$ua = get_ua();
		$this->assign('ua', $ua);
		// 判断登录
		$uid = is_login();
		if(!$uid){
			if (!cookie('__backurl__')) cookie('__backurl__', $_SERVER['REQUEST_URI']);
			if ($ua == 'ali'){
				$this->redirect(url('user/member/alilogin'));
			} else {
				$this->redirect(url('user/member/wxlogin'));
			}
		}
		// 获取用户信息
		$user = MemberModel::where('id', $uid)->find();
		$user['level'] = 0;
        $user['auth'] = 0;

		$vip = VipModel::where('member_id', $uid)->where('status', 1)->find();

		if ($vip) {
			// 判断是否自动升级
			$config = LevelModel::Config($vip['group']);
//            var_dump($config);exit;
            if(!empty($config)){
               $auto_up = $config['auto_up'];
               $direct = $config['direct'];
               $up_no = $config['up_no'];
            }else{
                $auto_up = 1;
                $direct = 5;
                $up_no = 9;
            }
			$time = time();
			if ($vip['auto_up'] == 1 && $auto_up && $vip['check_time'] < $time - 3600*23) { //每天升级一次
				$number = VipModel::where('pid', '=', $uid)->where('group', '>=', $vip['group'])->count('member_id');
				$number_child = VipModel::where('member_id', 'in', MemberModel::getChildsId($uid))->where('group', '>=', $vip['group'])->count('member_id');
				// 达到升级条件
				if ($number >= $direct && $number_child >= $up_no) {
					// 记录会员升级
					Db::name('user_vip_log')->strict(false)->insert(['uid' => $uid, 'group' => $vip['group'], 'up' => $vip['group'] + 1, 'time' => $time, 'number' => $number_child]);
					$vip->group = $vip['group'] + 1;
					$this->assign('levelUp', ['now' => LevelModel::level_list($vip['group']), 'up' => LevelModel::level_list($vip['group'] + 1), 'direct' => $number, 'all' => $number_child]);
				}
				$vip->check_time = $time;
				$vip->save();
                $group = LevelModel::level_list($vip->group);
				//4省代3市代2总代0认证会员1孵化代理
                $sendData = [
                    'template_id'   => '6iCuLOFSHI4rSLNEbgcE8TJ9EVU6kfEZwrHwNSr51Y8',//模板消息ID
                    'touser'    => $user['openid'],//用户openid
                    'data'=>[
                        'first'=>[
                            'value'=>'亲，让你久等了!',
                            'color'=>'#000000',
                        ],
                        'keyword1'=>[
                            'value'=>$group,//订单编号
                            'color'=>'#000000'
                        ],
                        'keyword2'=>[
                            'value'=>'升级成功！',//审核状态
                            'color'=>'#000000'
                        ],
                        'remark'=>[
                            'value'=>'安合元，祝您步步高升！！',//描述
                            'color'=>'#173177',
                        ],
                    ]
                ];
                $this->template($sendData);

			}
			$user['group'] = LevelModel::level_list($vip['group']);
			$user['level'] = $vip['group'];
			$shop = LevelModel::shopConfig($vip['shop']);
            $user['shop'] = $shop['name'];

		}

//		var_dump($user);exit;
		$this->assign('user', $user);
		
		// 设置个人中心菜单
		$menus = [];
		
		$this->assign('menus', $menus);
		if($ua == 'ali'){
			// 支付宝SDK支持
			$jssdk = $this->getAliSdk();
			if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
		}else{
			// 微信SDK支持
			$jssdk = $this->getWxSdk();
			if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
		}
		// 获取所有导航
		$nav = \app\cms\model\Nav::getNav();
		$this->assign('nav', $nav);
		$this->assign('active', 'member');
		return $this->fetch();
	}
	public function Alilogin()
	{
		$this->error('请使用微信登录');
	}
	
	/**
	 * 退出登录
	 */
	public function logout()
	{
	    session(null);
	    cookie('member_id', null);
	    cookie('member_signin_token', null);
	    $this->redirect(url('user/member/index'));
	}
    // 发送微信模板消息
    protected function template($data)
    {
        $wxsdk = new Wxsdk;
        return $wxsdk->template($data);
    }
	/**
	 * 用户扩展资料
	 * @package app\user\home
	 */
	public function userinfo()
	{

		$uid = is_login();
		if(!$uid ){
		    if (!cookie('?__backurl__')) cookie('__backurl__', $_SERVER['REQUEST_URI']);
			$this->redirect('index');
		}
		// 查找用户数据
		$MemberModel = new MemberModel;
		$userinfo = $MemberModel::where('id',$uid)->where('status', 1)->find();

		$pid = request()->get('pid');
		if ($pid > 0) cookie('pid', $pid);
		if ($this->request->isPost()) {
			//获取POST数据
			$data = request()->post();

			// 检查推荐人
			if (!empty($data['pid']) && $data['pid'] > 0) {
				
				if ($data['pid'] == $userinfo['id']) {
					$this->error('推荐人不能是自己');
				}
				
				// 检查Vip信息
                $vip = VipModel::where('member_id', '=', $data['pid'])->where('status', '=', 1)->where('group', '>', 1)->find();
				if ($vip) {
					// 获取自己的后代ID
					$ids = VipModel::getChildsId($uid);
					if (in_array($data['pid'], $ids)) {
						$this->error('推荐人在你的团队里, 不能互推！');
					}else{
                        //推荐返佣
                        $return_money = app_config('mall', 'return_money');
                        $vip->money = $return_money + $vip['money'];
                        $vip->save();
                    }
					$userinfo->pid 	= $data['pid'];
				} else {
					$this->error('推荐人暂无推荐权限');
				}
			}
			// 验证
			$data['id'] = $uid;

			$result = $this->validate($data, 'Member');
			if(true !== $result) $this->error($result);

			if ($userinfo['auth'] == 1) $this->error('已实名认证，请勿重复提交');
			// 更新用户信息
			$userinfo->realname	= $data['realname'];
			$userinfo->mobile 	= $data['mobile'];
			$userinfo->idcard 	= $data['idcard'];
            $userinfo->auth 	= 1;
			
		    if ($userinfo->save()) {
                $vipModel = new \app\user\model\Vip;
                $vip = $vipModel->where('member_id', '=', $userinfo['id'])->find();
                if (!$vip) {
                    $vipModel->member_id = $userinfo->id;
                    $vipModel->pid = $userinfo['pid'];
                    $vipModel->realname = $userinfo['realname'];
                    $vipModel->mobile = $userinfo['mobile'];
                    $vipModel->idcard = $userinfo['idcard'];
                    $vipModel->save();
                } else {
                    $vip->pid = $userinfo['pid'];
                    $vip->realname = $userinfo['realname'];
                    $vip->mobile = $userinfo['mobile'];
                    $vip->idcard = $userinfo['idcard'];
                    $vip->save();
                }
                $pinfo = $MemberModel::where('id',$data['pid'])->where('status', 1)->find();
                $sendData = [
                    'template_id'   => '7WoX4Dh96zD5gvqEpUeUFra4oV3HvuC7crJYpWMvrwM',//模板消息ID
                    'touser'    => $pinfo['openid'],//用户openid
                    'data'=>[
                        'first'=>[
                            'value'=>'申请加入您的团队',
                            'color'=>'#000000',
                        ],
                        'keyword1'=>[
                            'value'=>$userinfo->realname,//申请人
                            'color'=>'#000000'
                        ],
                        'keyword2'=>[
                            'value'=>$pinfo['realname'].':的团队成员！',//部门
                            'color'=>'#000000'
                        ],
                        'remark'=>[
                            'value'=>'欢迎您的加入！',//描述
                            'color'=>'#173177',
                        ],
                    ]
                ];
                $this->template($sendData);

		        $this->success('提交成功', cookie('__wxback__'));
		    } else {
		        $this->error('提交失败');
		    }
		}
		if($userinfo){
			if ($pid == 0) $pid = cookie('pid');
			if ($userinfo['pid'] == 0 && $pid != 0 && $userinfo['auth'] == 0) $userinfo['pid'] = $pid;
			if ($userinfo['pid'] != 0) {
				$userinfo['push_user'] = MemberModel::where('id', $userinfo['pid'])->value('realname');
			}
			$vip = VipModel::where('member_id', $uid)->where('status', 1)->find();
			if ($vip) {
				$userinfo['group'] = LevelModel::level_list($vip['group']);
			}
			$this->assign('user', $userinfo);
		}else{
			$this->error('账号被禁用');
		}
		// 获取所有导航
		$nav = \app\cms\model\Nav::getNav();
		$this->assign('nav', $nav);
		$this->assign('active', 'member');
		// 获取浏览器类型
		$ua = get_ua();
		$this->assign('ua', $ua);
		if($ua == 'ali'){
			// 支付宝SDK支持
			$jssdk = $this->getAliSdk();
			if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
		}else{
			// 微信SDK支持
			$jssdk = $this->getWxSdk();
			if($jssdk['code'] == 1) $this->assign('jssdk', $jssdk);
		}
		return $this->fetch(); // 渲染模板
	}
	/**
	 * 判断是否存在emoji表情
	 */
	private function emoji($str)
	{
		$length = mb_strlen($str);
		$array = [];
		for ($i=0; $i<$length; $i++) {
			$array[] = mb_substr($str, $i, 1, 'utf-8');
			if( strlen($array[$i]) >= 4 ){
				return true;
			}
		}  
		return false;
	}
	/**
	 * 获取分享参数
	 */
	protected function getWxSdk($url = null)
	{
	    $wxsdk = new Wxsdk;
		return $wxsdk->getWxSdk($url);
	}
	
	/**
	 * 查询系统消息
	 */
	public function message()
	{
		// 判断登录
		$uid = is_login();
		$this->assign('active', 'member');
		$vip = VipModel::where('member_id', '=', $uid)->find();
		if (!$vip) $this->error('权限不足');
		$map = [
			['send_type', '=',  'vip'],
			['uid_receive', '=',  $vip['group']],
		];
		$order = 'create_time desc';	
		$data_list = MessageModel::where($map)->order($order)->paginate(10);
		if (request()->isPost()){
			$ajax_list = $data_list->items();
			$ajax = [];
			foreach ($ajax_list as $key => $value) {
				$ajax[$key] = [
					'time'		=> format_time($value['create_time']),
					'type'		=> $value['type'],
					'content' 	=> $value['content'],
					'uid_send' 	=> get_nickname($value['uid_send']),
				];
			}
			$data['items'] = $ajax;
			$data['last_page'] = $data_list->lastPage();
			$data['total'] = $data_list->total();
			$data['current_page'] = $data_list->currentPage();
			$data['list_rows'] = $data_list->listRows();
			$this->success('加载成功', '', $data);
		}
		// 分享参数
		$share = [
			'title' => '大白家商城',
			'desc'	=> '大白家在线商城系统',
			'url'	=> real_url('mall/index/index'),
			'hide'	=>true,
		];
		$this->assign('share', $share);
		
		return $this->fetch();
	}
}
